package leecode

func addTwoNumbers2(l1 *ListNode, l2 *ListNode) *ListNode {
	l1 = reserveListNode(l1)
	l2 = reserveListNode(l2)
	result := sumTwo(l1, l2)
	return reserveListNode(result)
}

func sumTwo(l1, l2 *ListNode) *ListNode {
	dummy := &ListNode{}
	cur := dummy
	carry := 0 //进位
	for l1 != nil || l2 != nil || carry != 0 {
		if l1 != nil {
			carry += l1.Val
		}
		if l2 != nil {
			carry += l2.Val
		}
		cur.Next = &ListNode{
			Val: carry % 10,
		}
		carry = carry / 10
		cur = cur.Next
		if l1 != nil {
			l1 = l1.Next
		}
		if l2 != nil {
			l2 = l2.Next
		}
	}
	return dummy.Next
}

// 反转链表
func reserveListNode(list *ListNode) (pre *ListNode) {
	cur := list
	for cur != nil {
		next := cur.Next
		cur.Next = pre
		pre = cur
		cur = next
	}
	return pre
}
